import pandas as pd
from collections import Counter
from tqdm import tqdm

# 读取提供的电影和评分数据
movies_df = pd.read_csv('ml-25m/movies.csv')
ratings_df = pd.read_csv('ml-25m/ratings.csv')

# 筛选出评分大于等于4的记录
high_rated = ratings_df[ratings_df['rating'] >= 4]

# 汇总每个用户给出高评分的电影
user_high_rated_movies = high_rated.groupby('userId')['movieId'].apply(list)

# 分析每个用户最喜欢的电影类型
user_favorite_genres = {}

for user_id in tqdm(ratings_df['userId'].unique()):
    # 获取该用户高评分的电影ID
    movie_ids = user_high_rated_movies.get(user_id, [])

    genres_list = []
    for movie_id in movie_ids:
        # 获取电影的类型
        if movie_id in movies_df['movieId'].values:
            genres = movies_df[movies_df['movieId']
                               == movie_id]['genres'].values[0]
            genres_list.extend(genres.split('|'))

    # 如果用户没有高评分电影或者没有喜欢的电影类型，则记录为无偏好
    if not genres_list:
        user_favorite_genres[user_id] = "No Preference"
    else:
        # 计算出现最多的电影类型
        most_common_genres = Counter(genres_list).most_common(1)
        user_favorite_genres[user_id] = most_common_genres[0][0] if most_common_genres else "No Preference"

# 将用户喜欢的电影类型输出到CSV文件中
output_data = []
for user_id, favorite_genre in tqdm(user_favorite_genres.items()):
    sentence = f"The user likes {favorite_genre} genre movies"
    output_data.append(
        {"userId": user_id, "Favorite_Genre_Sentence": sentence})

output_df = pd.DataFrame(output_data)
output_csv_path = 'user_favorite_genres_new.csv'
output_df.to_csv(output_csv_path, index=False)
